﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;

namespace QueryBuilder.Core.Visualization
{
    /// <summary>
    /// 
    /// </summary>
    public class ViewModel : INotifyPropertyChanged
    {
        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <typeparam name="TValue">The type of the value.</typeparam>
        /// <typeparam name="TModel">The type of the model.</typeparam>
        /// <param name="target">The target.</param>
        /// <param name="value">The value.</param>
        /// <param name="propertySelector">The property selector.</param>
        /// <returns></returns>
        protected virtual bool SetValue<TValue, TModel>(
            ref TValue target, TValue value, Expression<Func<TModel>> propertySelector)
        {
            if (Equals(target, value))
            {
                return false;
            }

            var memberExpression = propertySelector.Body as MemberExpression;
            if (memberExpression != null)
            {
                string propertyName = memberExpression.Member.Name;
                target = value;
                this.RaisePropertyChanged(propertyName);
            }

            return true;
        }

        /// <summary>
        /// Raises the property changed.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        private void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}